/**
 * 处理南昌房地产信息，将所有的数据按照指定格式重新展示
 */

import { Driver } from "./db";
import * as fs from "fs";

const limit = 100;
let driver = new Driver();
const sourceDataTable = "ncfdcxxext";
const targetDataTable = "ncfdcanaysis";

let debug = false;
let containsTitle: string = "";

if (process.argv.length > 2) {
    debug = true;
    containsTitle = process.argv[2];
}


let condition: any = {};
if (debug) {
    condition["项目名称"] = containsTitle;
    console.log(`查询条件: 项目名称=${containsTitle}`);
}

let total = driver.countSync(sourceDataTable, condition);

if (!debug)
    driver.removeSync(targetDataTable, {});

let step = Math.round((total + limit - 1) / limit); // 总页数（以便分页）


class Logs {
    buffs: string[];
    logfile: string;
    constructor(logfile: string) {
        this.logfile = logfile;
        this.buffs = [];
    }

    append(msg: string): void {
        this.buffs.push(msg);
        this.buffs.push("\n");
    }

    log(msg: string): void {
        this.append(msg);
    }

    flush(): void {
        fs.writeFileSync(this.logfile, this.buffs.join());
    }
}

let map: any = {};
let cnt = 0, index = 0;
let log = new Logs("./log.txt");
for (let i = 0; i < step; i++) {
    console.log("process page: " + i + "/" + step);
    let start = i * limit;
    let items = driver.pagnateSync(sourceDataTable, condition, start, limit);
    (items as any[]).forEach(item => {
        let prefixTitle = item["项目名称"];
        let title = prefixTitle + " - " + item["发证日期"] + " - " + item["销售状态"];
        // if (debug) {
        //     log.log(`项目名称 ${title}`);
        // }
        let consoleLog = debug && (prefixTitle == containsTitle);
        let itm = map[title];
        index++;
        if (!itm) {
            delete item._id;
            item._collection = targetDataTable;
            item.title = title;
            let jzmj = parseFloat(item["建筑面积"] || 0.0);
            let xsckdj = parseFloat(item["销售参考单价"] || 0.0);
            item["建筑面积"] = jzmj;
            item["累计销售总价"] = jzmj * xsckdj;
            map[title] = item;
            cnt++;
            // if (consoleLog) {
            //     log.log(`名称: ${title} 建筑面积: ${jzmj}  销售参考单价: ${xsckdj} `);
            // }
        } else {
            let xszjg = parseFloat((<any>itm)["累计销售总价"] || 0.0);
            let jzmj = parseFloat(item["建筑面积"] || 0.0);
            let xsckdj = parseFloat(item["销售参考单价"] || 0.0);
            let xszjg2 = jzmj * xsckdj;
            xszjg += xszjg2;
            itm["建筑面积"] = jzmj + itm["建筑面积"];
            itm["累计销售总价"] = xszjg;
            if (consoleLog) {
                //log.log(`[${index}] 名称: ${title} 建筑面积: ${jzmj} + ${jzmj2} = ${jzmj3}  销售参考单价: ${xsckdj} + ${xsckdj2} = ${xsckdj3} `);
            }
            map[title] = itm;
        }
    });
}

if (debug)
    log.flush();

console.log("all finished [" + cnt + "]");

if (!debug) {
    for (let key in map) {
        let item = map[key];
        var inserted = driver.insertSync(item["_collection"], item);
        if (inserted) {
            console.log("item " + item.title + " inserted");
        } else {
            console.error("insert error: " + item.title + " [" + item.source + "]");
        }
    }
}

console.log("process finished.");
process.exit(0);